package cn.zwxky.android.staff.My;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.net.Token;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.utils.valid.Valid;
import com.zgscwjm.lsfbbasetemplate.view.Camera.LsfbCamera;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.zwxky.android.staff.Login.ForgetBean;
import cn.zwxky.android.staff.R;
import cn.zwxky.android.staff.Utils.LittleUtils;
import cn.zwxky.android.staff.Utils.NoDoubleClickUtils;
import cn.zwxky.android.staff.Utils.Permission;
import cn.zwxky.android.staff.Utils.PopWindowManager;
import cn.zwxky.android.staff.Utils.URLString;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 资料管理页面
 * Created by Administrator on 2017/3/15 0015.
 */
@ContentView(R.layout.aty_my_details)
public class MyDetailsActivity extends LsfbActivity {

    @ViewInject(R.id.fg_my_img_head)
    private SimpleDraweeView img_head;

    /**
     * 姓名
     */
    @ViewInject(R.id.aty_my_details_et_name)
    private EditText et_name;

    /**
     * 性别
     */
    @ViewInject(R.id.aty_my_details_text_sex)
    private TextView text_sex;

    /**
     * 部门
     */
    @ViewInject(R.id.aty_details_et_department)
    private TextView et_department;

    /**
     * 职位
     */
    @ViewInject(R.id.aty_my_details_et_position)
    private TextView et_position;

    /**
     * 手机
     */
    @ViewInject(R.id.aty_my_details_et_phone)
    private EditText et_phone;

    /**
     * 邮箱
     */
    @ViewInject(R.id.aty_my_details_et_email)
    private EditText et_email;


    /**
     * PopWindow管理类
     */
    private PopWindowManager replay;

    /**
     * 性别，1男、2女
     */
    private int select = 0;

    /**
     * 封装好的照相机
     */
    private LsfbCamera camera;

    /**
     * 头像存储
     */
    private String mimage = "";

    private Uri uri;

    private boolean isXiangce=true;

    private static final int REQUEST_CODE_WRITE_SETTINGS = 2;


    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    if (select == 1) {
                        text_sex.setText("男");
                    } else if (select == 2) {
                        text_sex.setText("女");
                    }
                    break;
            }
        }
    };


    @Override
    public void initView() {
        Permission permission = new Permission(MyDetailsActivity.this);
        permission.GetCAMEARPermission();

        LittleUtils.setsimpletitlebar(this, "资料管理");
        TextView textView = new TextView(this);
        textView.setText("保存");
        textView.setTextColor(getResources().getColor(R.color.white_color));
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收起软键盘
                InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.hideSoftInputFromWindow(et_name.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_phone.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_email.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_department.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_position.getWindowToken(), 0);
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    post();
                }

            }
        });
        getTitleBar().setRightView(textView, 0, 0, DensityUtils.dp2px(this, 10), 0);

        camera = new LsfbCamera() {
            @Override
            public void resultUri(Uri uri) {
                MyDetailsActivity.this.uri = uri;
            }
        };

    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_my_details_head, R.id.aty_my_details_text_sex})
    public void onClick(View view) {
        switch (view.getId()) {
            //修改头像
            case R.id.aty_my_details_head:
                camera.show(MyDetailsActivity.this, MyDetailsActivity.this);
                break;
            //修改性别
            case R.id.aty_my_details_text_sex:
                replay = new PopWindowManager(MyDetailsActivity.this, R.layout.pop_select_sex) {
                    @Override
                    public void onViewLister(View contentView, final PopWindowManager manager) {

                        final TextView pop_select_quxiao = (TextView) contentView.findViewById(R.id.pop_select_quxiao);
                        final TextView pop_select_yes = (TextView) contentView.findViewById(R.id.pop_select_yes);
                        final TextView text_man = (TextView) contentView.findViewById(R.id.pop_sex_text_man);
                        final TextView text_woman = (TextView) contentView.findViewById(R.id.pop_sex_text_woman);
                        final RelativeLayout RelativeLayout = (RelativeLayout) contentView.findViewById(R.id.RelativeLayout);

                        text_man.setBackgroundResource(R.color.white_color);
                        text_woman.setBackgroundResource(R.color.white_color);
                        select = 0;

                        pop_select_quxiao.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                manager.hideWindow();
                            }
                        });

                        pop_select_yes.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                handler.sendEmptyMessage(1000);
                                manager.hideWindow();
                            }
                        });

                        text_man.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                text_man.setBackgroundResource(R.color.bottom_unchecked_color2);
                                text_woman.setBackgroundResource(R.color.white_color);
                                select = 1;
                            }
                        });
                        text_woman.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                text_woman.setBackgroundResource(R.color.bottom_unchecked_color2);
                                text_man.setBackgroundResource(R.color.white_color);
                                select = 2;
                            }
                        });

                        RelativeLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                manager.hideWindow();
                            }
                        });

                    }
                };
                replay.showWindowsCenter(MyDetailsActivity.this.getWindow().getDecorView());
                break;
        }
    }

    @Override
    public void initData() {
        getData();
    }

    /**
     * 获取信息
     */
    public void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid", Config.getUserId());
        new BaseInternet().getData_Get(URLString.INFO, hashMap, MyDetailsBean.class, new MyDetailsEvent2<MyDetailsBean>(), true, true);
    }

    @EventAnnotation
    public void MyDetailsEvent(MyDetailsEvent2<MyDetailsBean> event) {
        switch (event.getCode()) {
            case 200:
                if (!event.getData().getImg().isEmpty()) {
                    img_head.setImageURI(Uri.parse(URLString.IMG_URL + event.getData().getImg()));
                } else {
                    img_head.setBackgroundResource(R.mipmap.img_my_details_head);
                }

                et_name.setText(event.getData().getName());
                if (event.getData().getSex().isEmpty()) {
                    text_sex.setText("请选择性别");
                }else if (event.getData().getSex().equals("男")){
                    text_sex.setText("男");
                }else if (event.getData().getSex().equals("女")){
                    text_sex.setText("女");
                }else {
                    text_sex.setText("请选择性别");
                }
                et_phone.setText(event.getData().getTel());
                et_department.setText(event.getData().getDepart_name());
                et_position.setText(event.getData().getJob_name());
                et_email.setText(event.getData().getMail());
                break;
            default:
                break;
        }
    }

    /**
     * 提交信息
     */
    public void post() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid",Config.getUserId());
        hashMap.put("img",mimage);
        hashMap.put("name",et_name.getText().toString());
        hashMap.put("sex",text_sex.getText().toString());
        hashMap.put("tel",et_phone.getText().toString());
        hashMap.put("email",et_email.getText().toString());

        new BaseInternet().getData(URLString.INFO_EDIT, hashMap, ForgetBean.class, new InfoEditEvent<ForgetBean>(), false);
    }

    @EventAnnotation
    public void InfoEditEvent(InfoEditEvent<ForgetBean> event) {
        switch (event.getCode()) {
            case 200:
                SN.SnackShow(img_head,event.getMsg());
                getData();
                break;
            default:
                SN.SnackShow(img_head,event.getMsg());
                break;
        }
    }

    /**
     * 头像选择回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);

        LsfbLog.e("requestCode" + requestCode);
        LsfbLog.e("resultCode" + resultCode);

        if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Settings.System.canWrite(this)) {
                LsfbLog.e("onActivityResult write settings granted");
            } else {
                LsfbLog.e("请求失败");
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LsfbCamera.REQUESTCODE:
                    LsfbLog.e(uri.toString());
                    isXiangce=false;
                    camera.crop(uri, 300);
                    break;
                case LsfbCamera.SYSTEMPHOTOS:
                    LsfbLog.e(data.getData().toString());
                    String url = "file://" + LsfbCamera.getPath(this, data.getData());
                    LsfbLog.e("22222222222222" + url);
                    uri = Uri.parse(url);
                    isXiangce=true;
                    camera.crop(uri, 300);
//                    File zipfile= ZipPic.zippng(uri.getPath());
//                    camera.crop(Uri.parse("file://"+zipfile.getPath()), 300);
                    break;
                case LsfbCamera.CROPIMG:
                    List<File> list = new ArrayList<>();
                    LsfbLog.e("---------------------------------------------:" + uri.getPath());
                    if (isXiangce){
                        try {
                            String url1 = "file://" + LsfbCamera.getPath(this, data.getData());
                            list.add(new File(Uri.parse(url1).getPath()));
                        }catch(Exception e){
                            list.add(new File(uri.getPath()));
                        }
                    }else {
                        list.add(new File(uri.getPath()));
                    }

//                    LsfbServerUpload.server(this, list, new IServerCall<String[]>() {
//                        @Override
//                        public void call(String[] strings) {
//                            LsfbLog.e("fsdfds");
//                            mimage = strings[0];
//                            post();
//                            LsfbLog.e("3333333333" + uri.getPath());
//                        }
//                    });
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("uid",Config.getUserId());
                    hashMap.put("img",list.get(0).getPath());
                    // TODO: 2017/3/28 0028 头像上传~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    new HttpClient().postFile(URLString.IMGUPLOAD + Token.getToken(URLString.IMGUPLOAD), hashMap, list, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            LsfbLog.e(e.getLocalizedMessage());
                            LsfbLog.e("上传失败");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            LsfbLog.e("上传success");
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().string());
//                                LsfbLog.e("上传结果" + response.body().string());
                                LsfbLog.e("上传结果" + jsonObject.toString());
                                if (jsonObject.getInt("code") == 200) {
                                    LsfbLog.e("得到回调");
                                    JSONObject img = jsonObject.getJSONObject("data");
                                    mimage = img.getString("img");
                                    post();
                                } else {
                                    LsfbLog.e("得到失败回调");
                                    T.showShort(MyDetailsActivity.this, jsonObject.getString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    break;
            }
        }
    }



}
